package fusion

import "io"

func Must(args ...interface{}) {
	if err := args[len(args)-1]; err != nil {
		panic(err)
	}
}

func Check(args ...interface{}) []interface{} {
	if err := args[len(args)-1]; err != nil {
		panic(err)
	}
	return args[:len(args)-1]
}

func Ingore(args ...interface{}) []interface{} {
	return args[:len(args)-1]
}

func If(b bool, t, f interface{}) interface{} {
	if b {
		return t
	}
	return f
}

func IfInt(b bool, t, f int) int {
	if b {
		return t
	}
	return f
}

func MinInt(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func MaxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func CopyBytes(src []byte) []byte {
	if src != nil {
		dst := make([]byte, len(src))
		copy(dst, src)
		return dst
	}
	return nil
}

func FromReader7BitEncodedInt(r io.Reader) (uint, error) {
	var value uint
	var count int
	for {
		var bytes [1]byte
		if _, err := io.ReadFull(r, bytes[:]); err != nil {
			return 0, err
		}
		value += uint(bytes[0]&0x7f) << (count * 7)
		if bytes[0] > 0x7f {
			count += 1
		} else {
			break
		}
	}
	return value, nil
}

func ToWriter7BitEncodedInt(value uint, w io.Writer) error {
	var buffer [10]byte
	var count int
	for {
		var flag byte
		if value > 0x7f {
			flag = 0x80
		}
		buffer[count] = flag | byte(value)
		count += 1
		if flag > 0 {
			value >>= 7
		} else {
			break
		}
	}
	if _, err := w.Write(buffer[:count]); err != nil {
		return err
	}
	return nil
}

func NotifyNonBlock(c chan bool) {
	if len(c) == 0 {
		select {
		case c <- true:
		default:
		}
	}
}

func WaitBlock(c chan bool) bool {
	select {
	case _, ok := <-c:
		return ok
	}
}
